package com.ligongmusic.service;

import java.io.IOException;

import com.ligongmusic.R;
import com.ligongmusic.activity.MusicActivity;
import com.ligongmusic.util.LoggerUtils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

public class MusicOnlineService extends Service implements OnBufferingUpdateListener, OnPreparedListener, OnCompletionListener {
    private Context mContext;
//    private PowerManager.WakeLock wakeLock;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        // 播放
//		LoggerUtils.getLog(MusicOnlineService.class).error("onPrepared");
        Log.e("LoggerUtils", "准备完成");
        try {
            mp.start();
            MusicThread thread = new MusicThread();
            Message msg = new Message();
            msg.what = LOAD_SUCCESS;
            mMessenger.send(msg);
            thread.start();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        isPrepare = false;
        // 播放完成
        if (isLoop)//如果设置单曲循环，则跳过方法
            return;
        // 获取下一首
//        try {
//            Message msg = new Message();
//            msg.what = PLAYER_NEXT;
//            mMessenger.send(msg);
//        } catch (RemoteException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        // TODO Auto-generated method stub
//        if (mp.getCurrentPosition() >= percent){
//            // 缓冲中
//            Log.e("LoggerUtils", "line 84 : " + "缓冲中" + percent);
//        }
//        Log.e("LoggerUtils", "line 86 : " + percent + "");
        if (mp.getCurrentPosition() == 0 || mp.getDuration() == 0)
            return;
        if ((mp.getCurrentPosition() / mp.getDuration()) * 100 >= percent){// 进入缓冲
            try {
                Message msg = new Message();
                msg.what = LOAD_ING;
                mMessenger.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean isPrepare = false;
    private MediaPlayer mPlayer;
    public static final int START_MUSIC = 0;
    public static final int PAUSE_MUSIC = 1;
    public static final int CONTINUE_MUSIC = 2;
    public static final int STOP_MUSIC = 3;
    public static final int SEEK_TO_PROGRESS = 4;
    public static final int DURATION_TYPE = 5;
    public static final int CURRENT_TIME_TYPE = 6;
    public static final int PLAYER_NEXT = 7;
    public static final int SEEK_RESUME = 8;
    public static final int CHANGE_SEEK = 9;
    public static final int EXIT_PLAYER = 10;
    public static final int LOAD_ING = 11;
    public static final int LOAD_SUCCESS = 12;
    private boolean isLoop = false;
    private String playIng = "";// 正在播放
    private Messenger mMessenger;

    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null)
            return super.onStartCommand(intent, flags, startId);
        int status = intent.getIntExtra("status", -1);
        if(status == EXIT_PLAYER){
            stopMusic();
        }else{

            // 改变播放设置
            int playerSetting = intent.getIntExtra("playerSetting", -1);
            if (playerSetting == 0) {
                //表示设置循环播放
                isLoop = true;
                mPlayer.setLooping(isLoop);
            } else if (playerSetting == -1) {
                // 设置非循环播放
                isLoop = false;
                mPlayer.setLooping(isLoop);
            } else {
                // 设置非循环播放
                isLoop = false;
                mPlayer.setLooping(isLoop);
            }
            switch (status) {
                case START_MUSIC:
                    // 播放音乐
                    playNewMusic(intent);
                    break;
                case PAUSE_MUSIC:
                    // 暂停
                    pauseMusic(intent);
                    break;
                case CONTINUE_MUSIC:
                    // 继续
                    restartMusic(intent);
                    break;
                case STOP_MUSIC:
                    // 停止
                    stopMusic();
                    break;
                case SEEK_TO_PROGRESS:
                    // 移动进度条
                    playMusicByProgress(intent);
                    break;
                default:
                    // 第一次创建时，获取到Activity中的Messenger对象
                    mMessenger = (Messenger) intent.getExtras().get("messenger");
                    break;
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 获取上下文
        mContext = getApplicationContext();
        // 此方法只被调用一次，初始化MediaPlayer
        mPlayer = new MediaPlayer();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
        mPlayer.setOnBufferingUpdateListener(this);
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnCompletionListener(this);
    }


    private void playNewMusic(Intent intent) {
        final String musicPath = intent.getStringExtra("musicName");
        if (mPlayer == null) {
//            WifiManager.WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
//            wifiLock.acquire();
            mPlayer = new MediaPlayer();
            mPlayer.setOnBufferingUpdateListener(this);
            mPlayer.setOnPreparedListener(this);
            mPlayer.setOnCompletionListener(this);
//            mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        }
        if (isPrepare){
            mPlayer.stop();
            isPrepare = false;
//            mPlayer.release();
//            mPlayer = null;
//            mPlayer = new MediaPlayer();
//            mPlayer.setOnBufferingUpdateListener(this);
//            mPlayer.setOnPreparedListener(this);
//            mPlayer.setOnCompletionListener(this);
        }
        if (mPlayer.isPlaying()) {
            mPlayer.stop();
            isPrepare = false;
        }
//		new Thread(new Runnable() {
//			@Override
//			public void run() {
        mPlayer.reset();
        try {
            mPlayer.setDataSource(musicPath);
            if (!isPrepare)
                mPlayer.prepareAsync();
            isPrepare = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
//			}
//		}).start();
    }

    private void pauseMusic(Intent intent) {
        if (mPlayer == null)
            playNewMusic(intent);
        else {
            mPlayer.pause();
            // 进度条时间
            MusicThread thread = new MusicThread();
            thread.start();
        }
    }

    private void stopMusic() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
        stopSelf();
    }

    private void restartMusic(Intent intent) {
        if (mPlayer == null || !isPrepare)
            playNewMusic(intent);
        else {
            mPlayer.start();
            // 进度条时间
            MusicThread thread = new MusicThread();
            thread.start();
        }
    }

    private void playMusicByProgress(Intent intent) {
        if (mPlayer == null || !isPrepare) {// 如果没有选择播放的音乐，通知activity改变界面
            try {
                Message msg = new Message();
                msg.what = SEEK_RESUME;
//				msg.obj = mPlayer.getCurrentPosition();// 发送当前时长
                mMessenger.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            LoggerUtils.getLog(MusicOnlineService.class).error(isPrepare + "");
            return;
        }
        LoggerUtils.getLog(MusicOnlineService.class).error(isPrepare + "");
//    	if(mPlayer.isPlaying()){// 如果正在播放，则播放滑动的进度条位置
//    		mPlayer.pause();
        if (mPlayer.isPlaying()) {
            mPlayer.seekTo(intent.getIntExtra("seek_time", mPlayer.getCurrentPosition()));
//    		mPlayer.start();
            MusicThread thread = new MusicThread();
            thread.start();
        } else {
            try {
                Message msg = new Message();
                msg.what = CHANGE_SEEK;
                msg.arg1 = intent.getIntExtra("seek_time", mPlayer.getCurrentPosition());// 发送当前时长
//				msg.arg2 = mPlayer.getDuration();// 发送总时长
//				msg.obj = mPlayer.isPlaying();
                mMessenger.send(msg);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
//    	}

    }

    class MusicThread extends Thread {
        @Override
        public void run() {
            while (mPlayer != null && mPlayer.isPlaying()) {
                try {
                    Message msg = new Message();
                    msg.what = CURRENT_TIME_TYPE;
                    msg.arg1 = mPlayer.getCurrentPosition();// 发送当前时长
                    msg.arg2 = mPlayer.getDuration();// 发送总时长
                    msg.obj = mPlayer.isPlaying();// 播放状态
                    mMessenger.send(msg);
                    SystemClock.sleep(1000);// 一秒发送一次Handler
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    }

//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        if (wakeLock == null) {
//            wakeLock.release();
//            wakeLock = null;
//        }
//    }
}
